package com.yunfinal.api.tpl;

import com.jfinal.kit.*;
import com.jfinal.plugin.activerecord.sql.ParaDirective;
import com.jfinal.template.Engine;
import com.yunfinal.api.tpl.kit.MyDateKit;
import com.yunfinal.api.tpl.kit.TplKit;
import com.yunfinal.api.tpl.template.TemplateFn;
import com.yunfinal.api.tpl.template.TemplateKit;
import com.yunfinal.api.tpl.template.directive.EvalDirective;
import com.yunfinal.api.tpl.template.directive.TryDirective;
import com.yunfinal.api.tpl.template.directive.db.*;

import java.io.File;

public class EngineConfig {
    public static void config(Engine me) {
        me.setDevMode(true);
        //开发模式，路径指向
        me.setBaseTemplatePath(getBaseTemplatePath());
        //常用工具类
        me.addSharedObject("StrKit", new StrKit());
        me.addSharedObject("HashKit", new HashKit());
        me.addSharedObject("LogKit", new LogKit());
        me.addSharedObject("ElKit", new ElKit());
        me.addSharedObject("JsonKit", new JsonKit());
        me.addSharedObject("TimeKit", new TimeKit());
        me.addSharedObject("DateKit", new MyDateKit());
        me.addSharedObject("TplKit", new TplKit());

        //自定义指令
        me.addDirective("eval", EvalDirective.class);
        me.addDirective("try", TryDirective.class);
        //数据库操作指令
        me.addDirective("find", FindDirective.class);
        me.addDirective("findFirst", FindFirstDirective.class);
        me.addDirective("paginate", PaginateDirective.class);
        me.addDirective("update", UpdateDirective.class);
        me.addDirective("dbTx", DbTxDirective.class);
        me.addDirective("dbConfigName", DbConfigName.class);
        me.addDirective("para", ParaDirective.class, true);

        //全局函数，请到TemplateFn中配置和书写，或者转调
        me.addSharedMethod(new TemplateFn());

        //模板方便单独调用
        TemplateKit.setEngine(me);
    }

    public static String getBaseTemplatePath() {
        try {
            String path = PathKit.getRootClassPath();
            String ret = new File(path).getParentFile().getParentFile().getCanonicalPath();
            // 支持 maven 项目在开发环境下探测 src/main/resources
            if (path.endsWith("/target/classes")) {
                return ret + "/src/main/resources";
            }
            if (path.endsWith("\\target\\classes")) {
                return ret + "\\src\\main\\resources";
            }
            return path;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
